﻿using Card.Make.Pro.Application.Helper;
using DevExpress.Spreadsheet;
using DevExpress.XtraCharts;
using DevExpress.XtraEditors;
using DevExpress.XtraPrinting;
using DevExpress.XtraPrintingLinks;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Windows.Forms;

namespace Card.Make.Pro.Form
{
    public partial class Frm_QuickOut : DevExpress.XtraEditors.XtraForm
    {
        public Frm_QuickOut()
        {
            InitializeComponent();
        }
        private Frm_SqlConn frm = new Frm_SqlConn();
        private string connStr;
        string FileName = Environment.CurrentDirectory.ToString();
        SqlHelper sqlHelper = new SqlHelper();
        private void barButtonItem2_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            frm.StartPosition = FormStartPosition.CenterScreen;
            if (frm.ShowDialog() == DialogResult.OK)
            {
                connStr = frm.connString;
            }
            else
            {
                return;
            }
            if (connStr.Length == 0)
            {

                return;
            }

            dtBindToExcel(connStr);
        }

        public static string DataTable2Xml(DataTable vTable)
        {
            if (null == vTable) return string.Empty;
            if (string.IsNullOrEmpty(vTable.TableName))
            {
                vTable.TableName = "tbName";
            }
            StringWriter writer = new StringWriter();
            vTable.WriteXml(writer);
            string xmlstr = writer.ToString();
            writer.Close();
            return xmlstr;
        }

        private void dtBindToExcel(string connStr)
        {
            DataTable dt = sqlHelper.GetQueryResult(connStr);
            foreach (DataRow row in dt.Rows)
            {
                // 0-正常,1-已挂失,2-已注销,3-申请制证
                if (dt.Columns.Contains("证卡状态"))
                {
                    switch (row["证卡状态"].ToString())
                    {
                        case "0":
                            row["证卡状态"] = "正常";
                            break;
                        case "1":
                            row["证卡状态"] = "已挂失";
                            break;
                        case "2":
                            row["证卡状态"] = "已注销";
                            break;
                        case "3":
                            row["证卡状态"] = "申请制证";
                            break;
                    }
                }
                // 0:未知,1:男,2:女
                if (dt.Columns.Contains("性别"))
                {
                    switch (row["性别"].ToString())
                    {
                        case "0":
                            row["性别"] = "未知";
                            break;
                        case "1":
                            row["性别"] = "男";
                            break;
                        case "2":
                            row["性别"] = "女";
                            break;

                    }
                }
                // 0-否,1-是
                if (dt.Columns.Contains("是否已打印"))
                {
                    switch (row["是否已打印"].ToString())
                    {
                        case "0":
                            row["是否已打印"] = "否";
                            break;
                        case "1":
                            row["是否已打印"] = "是";
                            break;
                    }
                }
                // 0-否,1-是
                if (dt.Columns.Contains("是否已发放"))
                {
                    switch (row["是否已发放"].ToString())
                    {
                        case "0":
                            row["是否已发放"] = "否";
                            break;
                        case "1":
                            row["是否已发放"] = "是";
                            break;
                    }
                }
            }
            gridControl1.DataSource = dt;

        }
        public void ExportToExcel(string title, params IPrintable[] panels)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.FileName = title;
            saveFileDialog.Title = "导出Excel";
            saveFileDialog.Filter = "Excel文件(*.xlsx)|*.xlsx|Excel文件(*.xls)|*.xls";
            DialogResult dialogResult = saveFileDialog.ShowDialog();
            if (dialogResult == DialogResult.Cancel)
                return;
            string FileName = saveFileDialog.FileName;
            PrintingSystem ps = new PrintingSystem();
            CompositeLink link = new CompositeLink(ps);
            ps.Links.Add(link);
            foreach (IPrintable panel in panels)
            {
                link.Links.Add(CreatePrintableLink(panel));
            }
            link.Landscape = true;//横向          
                                  //判断是否有标题，有则设置        
                                  //link.CreateDocument(); //建立文档
            try
            {
                int count = 1;
                //在重复名称后加（序号）
                while (File.Exists(FileName))
                {
                    if (FileName.Contains(")."))
                    {
                        int start = FileName.LastIndexOf("(");
                        int end = FileName.LastIndexOf(").") - FileName.LastIndexOf("(") + 2;
                        FileName = FileName.Replace(FileName.Substring(start, end), string.Format("({0}).", count));
                    }
                    else
                    {
                        FileName = FileName.Replace(".", string.Format("({0}).", count));
                    }
                    count++;
                }
                if (FileName.LastIndexOf(".xlsx") >= FileName.Length - 5)
                {
                    XlsxExportOptions options = new XlsxExportOptions();
                    link.ExportToXlsx(FileName, options);
                }
                else
                {
                    XlsExportOptions options = new XlsExportOptions();
                    link.ExportToXls(FileName, options);
                }
                if (DevExpress.XtraEditors.XtraMessageBox.Show("保存成功，是否打开文件？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                    System.Diagnostics.Process.Start(FileName);//打开指定路径下的文件
            }
            catch (Exception ex)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message);
            }
        }


        PrintableComponentLink CreatePrintableLink(IPrintable printable)
        {
            ChartControl chart = printable as ChartControl;
            if (chart != null)
                chart.OptionsPrint.SizeMode = DevExpress.XtraCharts.Printing.PrintSizeMode.Stretch;
            PrintableComponentLink printableLink = new PrintableComponentLink() { Component = printable };
            return printableLink;
        }
        private void barButtonItem3_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (string.IsNullOrEmpty(connStr))
                return;
            dtBindToExcel(connStr);
        }

        private void barButtonItem1_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ExportToExcel("综合制证系统导出表格" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx", this.gridControl1);



            //System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();

            //dialog.Description = "请选择导出目录";
            //if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            //{
            //    string path = dialog.SelectedPath;
            //    //spreadsheetControl1.SaveDocument(path + "\\综合制证系统导出表格"+DateTime.Now.ToString("yyyyMMddHHmmss")+".xlsx", DocumentFormat.Xlsx);
            //    MessageBox.Show("表格已成功导出至:\n" + path);
            //}
        }


        /// <summary>
        /// 高级搜索
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem4_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var frm = new Frm_QuickOutWhereExtend();
            if (frm.ShowDialog() == DialogResult.OK)
            {
                LoadingHelper.Open();
                QueryExtend(frm.QueryWhere);
                LoadingHelper.Close();

            }
        }

        /// <summary>
        /// 高级搜索
        /// </summary>
        /// <param name="where">限制条件</param>
        private void QueryExtend(string where)
        {
            var sql = $@"SELECT {(string.IsNullOrWhiteSpace(where) ? " TOP 1000" : "")}  [C_ID] AS 编号
      ,[CardNO] AS  证卡编号
      ,[CardID] AS 芯片号
      ,[CardType] AS 证卡类型
      ,[CardGroup] AS 组别
      ,[CardUnit] AS 单位
      ,[CardDepart] AS 部门
      ,[ContactTel] AS 联系电话
      ,[CardMemo] AS 备注
      ,[Photo] AS 照片
,CONVERT(VARCHAR(2), [CardState]) AS 证卡状态
      ,[StartUseDT] AS 开始时间
      ,[ExpireDT] AS 失效时间
      ,[CreateDT] AS 创建时间
     ,CONVERT(VARCHAR(10),[IFPrinted]) AS 是否已打印
      ,[PrintDT] AS 打印时间
      ,CONVERT(VARCHAR(10),[IFGranted]) AS 是否已发放
      ,[GrantedDT] AS 发放时间
      ,[UserName] AS  用户姓名
      ,[UserBirthday] AS 出生日期
 ,CONVERT(VARCHAR(10),[UserSex]) AS 性别
      ,[UserCertifyCardType] AS 身份证件类型
      ,[UserCertifyCardNo] AS 证件号码
      ,[UserCareer] AS 职务
      ,[CarNo] AS 车辆编号
      ,[CarDesc] AS 车辆描述
      ,[CarDriver] AS 驾驶人
      ,[UserDefine1] AS 用户自定义1
      ,[UserDefine2] AS 用户自定义2
      ,[UserDefine3] AS 用户自定义3
      ,[UserDefine4] AS 用户自定义4
      ,[UserDefine5] AS 用户自定义5
      ,[UserDefine6] AS 用户自定义6
      ,[UserDefine7] AS 用户自定义7
      ,[UserDefine8] AS 用户自定义8
      ,[UserDefine9] AS 用户自定义9
      ,[UserDefine10] AS 用户自定义10
      ,[UserDefine11] AS 用户自定义11
      ,[UserDefine12] AS 用户自定义12
      ,[AppVerID] AS 受理单号
      ,[AppErr] AS 异常备注
  FROM [dbo].[Card_Table] WHERE 1=1 ";
            sql += where;
            dtBindToExcel(sql);
        }

        private void gridControl1_Click(object sender, EventArgs e)
        {




        }
    }
}